package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "菜品接口")
@RestController(value = "UserDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;


    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTmplate;

    /**
     * 根据菜品id查询菜品信息、分类名称、口味
     * @param categoryId
     * @return
     */
    @ApiOperation("根据菜品id查询菜品信息、分类名称、口味")
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){

        //1.构造redis的key，key == dish_categoryId
        String key = "dish_" + categoryId;

        //2.查询Redis数据库是否存在菜品数据
        ValueOperations valueOperations = redisTmplate.opsForValue();
        List<DishVO> list = (List<DishVO>) valueOperations.get(key);
        if(list != null && list.size() > 0){
            //3.如果存在，直接返回
            return Result.success(list);
        }


        //4.如果不存在查询mysql数据库
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)//只查询处于起售中的菜品
                .build();

        list = dishService.listWithFlavor(dish);

        //5.并将查询后的数据存入redis数据库
        valueOperations.set(key,list);

        return Result.success(list);
    }
}
